package com.example.seakdreamandroid.voiceCommunity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.seakdreamandroid.Constant;
import com.example.seakdreamandroid.MainActivity;
import com.example.seakdreamandroid.R;
import com.example.seakdreamandroid.entity.AudioInfo;
import com.example.seakdreamandroid.entity.User;
import com.example.seakdreamandroid.whiteNoise.SleepFriendCreation;
import com.example.seakdreamandroid.whiteNoise.WhiteNoiseFreeConbinationChannel;
import com.example.seakdreamandroid.whiteNoise.WhiteNoiseSleepFriendChannel;
import com.example.seakdreamandroid.whiteNoisePlayer.WhiteNoisePlayerActivity;
import com.example.seakdreamandroid.whiteNoisePlayer.WhiteNoisePlayerService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class VoiceRemarkActivity extends AppCompatActivity {
    private ImageView musicPic1,musicPic2,musicPic3;
    private Context mContext;
    private static ListView listView;
    private static List<VoiceRemark> mlist;
    private static VoiceRemarkAdpter adpter;
    private static SmartRefreshLayout refreshLayout;
    private static final int REFRESH = 5;
    private static boolean isRefresh = true;
    private int currentNum = 1;
    private static ImageView player;
    private Intent intent;
    private Bundle bundle;
    private static ObjectAnimator animator;
    private ImageView musicActivity;
    private WhiteNoiseSleepFriendChannel whiteNoiseSleepFriendChannel;
    private TextView title;
    private TextView name;
    private TextView time;
    private TextView text;
   // private TextView count;
    //private TextView save;
    private static TextView voiceNum;
    private ImageView head;
    private EditText editText;
    private Button send;
    private User user;
    private ImageView returnButton;
    private ArrayList<AudioInfo> audioInfos = null;
    private WhiteNoisePlayerService.WhiteNoiseControl controller;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_voice_remark);
        controller = WhiteNoisePlayerService.getController();
        WhiteNoisePlayerService.registerForListener(handler);
        init();
        mlist = new ArrayList<VoiceRemark>();
        setData();
        adpter = new VoiceRemarkAdpter(mContext,mlist);
        listView.setAdapter(adpter);
        setListener();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        WhiteNoisePlayerService.removeForListener(handler);
    }

    public void init(){
        mContext = VoiceRemarkActivity.this;
        musicPic1 = findViewById(R.id.voice_remark_music1);
        musicPic2 = findViewById(R.id.voice_remark_music2);
        musicPic3 = findViewById(R.id.voice_remark_music3);
        listView = findViewById(R.id.voice_remark_listview);
        refreshLayout = findViewById(R.id.voice_remark_smart);
        player = findViewById(R.id.voice_remark_player);
        title = findViewById(R.id.voice_remark_title);
        name = findViewById(R.id.voice_remark_name);
        time = findViewById(R.id.voice_remark_time);
        text = findViewById(R.id.voice_remark_text);
        //count = findViewById(R.id.voice_remark_listen_count);
        //save = findViewById(R.id.voice_remark_collect_count);
        head = findViewById(R.id.voice_remark_head);
        send = findViewById(R.id.voice_remark_button);
        editText = findViewById(R.id.voice_remark_edittext);
        voiceNum = findViewById(R.id.voice_remark_num);
        returnButton = findViewById(R.id.voice_remark_return);
        intent = getIntent();
        bundle = intent.getBundleExtra("sleep");
        whiteNoiseSleepFriendChannel = (WhiteNoiseSleepFriendChannel) bundle.getSerializable("whiteSleep");
        //获取详细的音频信息
        String URL = Constant.BASE_URL +  "WhiteNoise/FreeConbination/findFreeConbinationById/" + whiteNoiseSleepFriendChannel.getSelectedId1() + "/" + whiteNoiseSleepFriendChannel.getSelectedId2() + "/" + whiteNoiseSleepFriendChannel.getSelectedId3();
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(URL)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e("onFailure","请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String responseBody = response.body().string();
                Gson gson = new Gson();
                Type type= new TypeToken<ArrayList<AudioInfo>>(){}.getType();
                audioInfos = gson.fromJson(responseBody,type);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(audioInfos.size() >= 1){
                            Glide.with(VoiceRemarkActivity.this)
                                    .load(audioInfos.get(0).getAudioPic())
                                    .into(musicPic1);
                        }
                        if(audioInfos.size() >= 2){
                            Glide.with(VoiceRemarkActivity.this)
                                    .load(audioInfos.get(1).getAudioPic())
                                    .into(musicPic2);
                        }
                        if(audioInfos.size() >= 3){
                            Glide.with(VoiceRemarkActivity.this)
                                    .load(audioInfos.get(2).getAudioPic())
                                    .into(musicPic3);
                        }
                    }
                });
            }
        });
        title.setText(whiteNoiseSleepFriendChannel.getTitle());
        name.setText(whiteNoiseSleepFriendChannel.getUserName());
        time.setText(whiteNoiseSleepFriendChannel.getTime());
        text.setText(whiteNoiseSleepFriendChannel.getContent());
        //count.setText(whiteNoiseSleepFriendChannel.getCount());
        //save.setText(whiteNoiseSleepFriendChannel.getSave());

        byte[] bs = Base64.decode(whiteNoiseSleepFriendChannel.getHead(), Base64.DEFAULT);
        for (int i = 0; i < bs.length; ++i) {
            if (bs[i] < 0) {
                bs[i] += 256;
            }
        }
        Bitmap bitmap = BitmapFactory.decodeByteArray(bs,0,bs.length);

        Glide.with(mContext).load(bitmap).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(head);
        musicActivity = findViewById(R.id.voice_remark_musicactivity);
        //左上角音乐动画
        animator = ObjectAnimator.ofFloat(musicActivity,"rotation",0f,360.0f);
        animator.setDuration(10000);
        animator.setInterpolator(new LinearInterpolator());
        animator.setRepeatCount(-1);
        System.out.println(WhiteNoisePlayerService.getPlayState());
        if(WhiteNoisePlayerService.getPlayState() == WhiteNoisePlayerService.PLAYING && playingAudioIsThis()){
            player.setBackgroundResource(R.mipmap.voiceplayer2);
        }else{
            player.setBackgroundResource(R.mipmap.voiceplayer);
        }
    }
    public Handler handler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理子线程发送的消息,对各种事件监听
            switch (msg.what) {
                case WhiteNoisePlayerService.PREPARED_EVENT:
                    //准备完成事件
                case WhiteNoisePlayerService.CONTINUE_EVENT:
                    //发生开始继续播放事件
                    player.setBackgroundResource(R.mipmap.voiceplayer2);
                    animator.start();
                    break;
                case WhiteNoisePlayerService.START_EVENT:
                    //开始准备事件
                case WhiteNoisePlayerService.PAUSE_EVENT:
                    //发生暂停播放事件
                    player.setBackgroundResource(R.mipmap.voiceplayer);
                    animator.pause();
                    break;
                case WhiteNoisePlayerService.ERROR_EVENT:
                    player.setBackgroundResource(R.mipmap.voiceplayer);
                    animator.pause();
                    Toast.makeText(VoiceRemarkActivity.this, "播放器出错了，啥错我不知道", Toast.LENGTH_LONG).show();
                    break;
                case REFRESH:
                    //刷新Listview
                    voiceNum.setText(mlist.size() + "");
                    adpter.notifyDataSetChanged();
                    if (isRefresh) {
                        refreshLayout.finishRefresh();
                    } else {
                        refreshLayout.finishLoadMore();
                    }
                    break;
            }
        }
    };

    private void setListener() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //下拉刷新时回调,需要请求最新的数据
                isRefresh = true;
                currentNum = 1;

            }

        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //上拉加载更多时回调，需要请求更多的数据，分页查询
                isRefresh = false;
                currentNum++;//页码加1

//                getData();

            }
        });
        player.setOnClickListener(new MyListener());
        musicActivity.setOnClickListener(new MyListener());
        send.setOnClickListener(new MyListener());
        returnButton.setOnClickListener(new MyListener());

    }

    private boolean playingAudioIsThis(){
        System.out.println(whiteNoiseSleepFriendChannel.getId());
        System.out.println(WhiteNoisePlayerService.getChannel());
        System.out.println(WhiteNoisePlayerService.getChannelInfoId());
        return "SleepFriendCreation".equals(WhiteNoisePlayerService.getChannel()) && WhiteNoisePlayerService.getChannelInfoId().equals(whiteNoiseSleepFriendChannel.getId());
    }
    private class MyListener implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.voice_remark_player:
                    if(playingAudioIsThis()){
                        //播放器的歌曲是当前页面的歌曲
                        switch(WhiteNoisePlayerService.getPlayState()){
                            case WhiteNoisePlayerService.NONE:
                                Toast.makeText(VoiceRemarkActivity.this,"没有白噪音被选中，怎么可能？",Toast.LENGTH_LONG).show();
                                break;
                            case WhiteNoisePlayerService.PREPARING:
                                Toast.makeText(VoiceRemarkActivity.this,"歌曲正在准备中，请稍等",Toast.LENGTH_LONG).show();
                                break;
                            case WhiteNoisePlayerService.PAUSE:
                                controller.continuePlay(true);
                                break;
                            case WhiteNoisePlayerService.PLAYING:
                                controller.pausePlay(true);
                                break;
                        }
                    }else {
                        //播放器的歌曲不是当前页面的歌曲
                        //先检查下音频详细加载是否完成
                        if(audioInfos != null)controller.play(audioInfos,"SleepFriendCreation",whiteNoiseSleepFriendChannel.getId(),true);
                    }
                    break;
                case R.id.voice_remark_musicactivity:
                    Intent intent = new Intent(mContext, WhiteNoisePlayerActivity.class);
                    //给播放页面发送消息
                    Bundle bundle1 = new Bundle();
                    startActivity(intent);
                    break;
                case R.id.voice_remark_button:
                    user = (User) getApplication();
                    String URL = Constant.BASE_URL + "WhiteNoise/VoiceRemark/addVoiceRemark?";

                    FormBody body = new FormBody.Builder()
                            .add("sleepFriendId",whiteNoiseSleepFriendChannel.getId())
                            .add("userId",user.getUserId())
                            .add("userRemark",editText.getText().toString())
                            .build();
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(URL)
                            .post(body)
                            .build();
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                            Log.e(VoiceRemarkActivity.class.getName(),"发送评论失败");
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                            String responseBody = response.body().string();
                            if (responseBody.equals("ok")){
                                setData();
                            }
                        }
                    });

                    InputMethodManager im = (InputMethodManager) getSystemService(VoiceRemarkActivity.this.INPUT_METHOD_SERVICE);
                    editText.setText("");
                    im.hideSoftInputFromWindow(editText.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);

                    break;
                case R.id.voice_remark_return:
                    finish();
                    break;


            }
        }
    }



    private void setData() {
        String URL = Constant.BASE_URL +  "WhiteNoise/VoiceRemark/findVoiceRemarkBySleepId/" + whiteNoiseSleepFriendChannel.getId();
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(URL)

                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e("onFailure","请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String responseBody = response.body().string();
                Gson gson = new Gson();
                Type type= new TypeToken<List<VoiceRemarkTemp>>(){}.getType();
                List<VoiceRemarkTemp> temps = gson.fromJson(responseBody,type);
                mlist.clear();
                mlist.addAll(getData(temps));
                Message message = handler.obtainMessage();
                message.what = REFRESH;
                handler.sendMessage(message);

            }
        });

    }

    private List<VoiceRemark> getData(List<VoiceRemarkTemp> temps) {
        List<VoiceRemark> list = new ArrayList<>();

        for(VoiceRemarkTemp voiceRemarkTemp : temps){

            VoiceRemark voiceRemark = new VoiceRemark();
            String URL = Constant.BASE_URL + "WhiteNoise/SleepFriendCreation/findUserInfoById/" + voiceRemarkTemp.getUserId();
            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(URL)
                    .build();
            Call call = okHttpClient.newCall(request);
            //这里没有用异步请求  异步请求很难拿到信息后进行更新
            Response response = null;
            try {
                response = call.execute();
                String responsseBody = response.body().string();

                JSONObject result = new JSONObject(responsseBody);
                voiceRemark.setHead(result.getString("headshot"));
                voiceRemark.setName(result.getString("userName"));
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy:MM:dd hh:mm:ss");
                String date = simpleDateFormat.format(voiceRemarkTemp.getPostTime());
                voiceRemark.setTime(date);
                voiceRemark.setContent(voiceRemarkTemp.getUserRemark());

                list.add(voiceRemark);
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }



        }
        return list;
    }
}